var QQMapWX = require('../utils/qqmap-wx-jssdk.js');

//获取应用实例
var tcity = require("../utils/citys.js");
const app = getApp()
Page({

  data: {
    url: app.globalData.requestURL + '/upload/uploadFile2Qiniu',
    array: ['个人用户', '企业用户'],
    index: 0,
    hiddenmodalput: true,
    imageListFap: [],//（买方身份证正反面，合同签字照片）
    countIndexFap: 3,//数量
    buyerImgsUrl: "",
    imageList: [],//（个人身份证正反面，手持身份证和机器合照）
    countIndex: 4,//上传图片个人照数量
    imgsUrl: '',
    imageListDevice: [],//设备前后左右照片，铭牌照片，大驾号照片，发动机铭牌
    countIndexDevice: 7,//上传设备图片数量
    equipmentImgsUrl: '',
    swtichTag: true,
    deviceType: ['挖掘机', '装载机', '矿用自卸车', '推土机', '压路机', '平地机', '混凝土机械', '桩工机械', '凿岩机械', '摊铺机', '俩头忙', '旋挖钻', '叉车'],
    indexDeviceType: 0,
    // walkWayType: ['履带式', '轮式', '水陆式'],
    walkWayType: ['轮式','履带式'],
    indexWalkWayType: 0,
    exhaustEmissionType: ['已检测', '未检测'],
    indexExhaustEmissionType: 0,
    fuelType: ['柴油', '汽油', '天然气'],//, '电'
    indexFuelType: 0,
    mortgageType: ['未抵押', '已抵押'],//, '电'
    indexMortgageType: 0,
    date: '2016-09-01',
    dateBuy: '2016-09-01',
    provinces: [],
    province: "",
    citys: [],
    city: "",
    countys: [],
    county: '',
    value: [0, 0, 0],
    values: [0, 0, 0],
    condition: false,
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  chooseImageFap: function () {
    var that = this
    if (this.data.imageListFap.length < this.data.countIndexFap) {
      wx.chooseImage({
        sourceType: ['camera'],
        sizeType: ['original', 'compressed'],
        count: this.data.countIndexFap,
        success: function (res) {
          console.log(res)
          console.log(res)
          that.setData({
            imageListFap: that.data.imageListFap.concat(res.tempFilePaths),
            name: "file",
            path: res.tempFilePaths,
            imagesType: "0"
          })
          app.uploadimg(that.data);
          app.imgResponseUrlReadyCallback = imgResponseUrl => {
            that.setData({
              buyerImgsUrl: that.data.buyerImgsUrl + imgResponseUrl.data + ','
            })
            console.log("返回图片url" + that.data.buyerImgsUrl)
          };
        }
      })
    } else {
      wx.showToast({
        title: '最多上传' + this.data.countIndexFap + '张图片',
        icon: 'loading',
        duration: 3000
      });
    }
  },
  chooseImage: function () {
    var that = this
    if (this.data.imageList.length < this.data.countIndex) {
      wx.chooseImage({
        sourceType: ['camera'],
        sizeType: ['original', 'compressed'],
        count: this.data.countIndex,
        success: function (res) {
          console.log(res)
          that.setData({
            imageList: that.data.imageList.concat(res.tempFilePaths),
            name: "file",
            path: res.tempFilePaths,
            imagesType: "0"
          })
          app.uploadimg(that.data);
          app.imgResponseUrlReadyCallback = imgResponseUrl => {
            that.setData({
              imgsUrl: that.data.imgsUrl + imgResponseUrl.data + ','
            })
            console.log("返回图片url" + imgResponseUrl.data)
          };

        }
      })
    } else {
      wx.showToast({
        title: '最多上传' + this.data.countIndex + '张图片',
        icon: 'loading',
        duration: 3000
      });
    }
  },
  chooseImageDevice: function () {
    var that = this
    if (this.data.imageListDevice.length < this.data.countIndexDevice) {
      wx.chooseImage({
        sourceType: ['camera'],
        sizeType: ['original', 'compressed'],
        count: this.data.countIndexDevice,
        success: function (res) {
          console.log(res)
          that.setData({
            imageListDevice: that.data.imageListDevice.concat(res.tempFilePaths),
            name: "file",
            path: res.tempFilePaths,
            imagesType: "0"
          })
          app.uploadimg(that.data);
          app.imgResponseUrlReadyCallback = imgResponseUrl => {
            that.setData({
              equipmentImgsUrl: that.data.equipmentImgsUrl + imgResponseUrl.data + ','
            })
            console.log("返回图片url" + that.data.equipmentImgsUrl)
          };

        }
      })
    } else {
      wx.showToast({
        title: '最多上传' + this.data.countIndexDevice + '张图片',
        icon: 'loading',
        duration: 3000
      });
    }
  },
  previewImageFap: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.imageListFap
    })
  },
  previewImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  },
  previewImageDevice: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.imageListDevice
    })
  },
  switchChange: function (e) {
    var that = this
    if (!e.detail.value) {
      wx.showModal({
        title: "发票办理流程",
        content: '1、请联系属地办事机构，尽快签署声明书、委托书、价值价格咨询报告。\r\n2、服务咨询电话：15048181888',
        // content: '1、关注内蒙古工程机械公众号。\r\n 2、下载委托书模板，合同模板。\r\n 3、委托书原件，合同原件,买方身份证正反面复印件 邮寄到公司。\r\n 4、公司地址：内蒙古包头市昆区阿尔丁大街沼潭东路18稀土高新区国家科技创业服务中心D座 1楼众创空间 内蒙古特勤机械设备管理服务有限公司。\r\n 5、联系方式：156-6131-8621。 \r\n 6、收件人：李素军。',
        showCancel: false,
        confirmText: "我已知晓",
        success: function () {
          that.setData({
            swtichTag: false
          })
          console.log(that.data.swtichTag)
        }
      })
    } else {
      that.setData({
        swtichTag: true
      })
      console.log(that.data.swtichTag)
    }
  },
  bindPickerChangeDeviceType: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      indexDeviceType: e.detail.value
    })
  },
  bindPickerChangeWalkWayType: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      indexWalkWayType: e.detail.value
    })
  },
  bindPickerChangeExhaustEmissionType: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      indexExhaustEmissionType: e.detail.value
    })
  },
  bindPickerChangeFuelType: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      indexFuelType: e.detail.value
    })
  },
  bindPickerChangeMortgageType: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      indexMortgageType: e.detail.value
    })
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindDateBuyChange: function (e) {
    this.setData({
      dateBuy: e.detail.value
    })
  },

  submit: function (e) {
    var name = e.detail.value.registerName
    var phone = e.detail.value.registerPhone
    var address = e.detail.value.address
    var idCardNum = e.detail.value.identification
    var engineModel = e.detail.value.engineSubject
    var enginePower = e.detail.value.power
    var enginePlateNum = e.detail.value.enginePlateNum
    var workDayTime = e.detail.value.workTime
    var equipmentQuality = e.detail.value.equipmentQuality
    var factoryNumber = e.detail.value.factoryNum




    console.log("身份证号：" + workDayTime)
    console.log("手机号：" + phone)

    var nameVer = /^[\u4E00-\u9FA5]{1,8}$/;
    var numNameVer =/^[\u4E00-\u9FA50-9]+$/;
    var numNameSymVer = /^(?![0-9]+$)[\u4E00-\u9FA5-0-9]+$/;
    var letNumVer = /^[0-9A-Za-z]+$/;
    var letNumSymVer = /^(?![0-9]+$)(?![a-zA-Z]+$)[-a-zA-Z0-9]+$/;
    var phoneVer = /^[1][3,4,5,7,8][0-9]{9}$/;
    var idCaedVer = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;


    // if (!nameVer.test(name)) {
    //   wx.showToast({
    //     title: '姓名不正确',
    //     icon: 'loading'
    //   })
    // } else if (!phoneVer.test(phone)) {
    //   wx.showToast({
    //     title: '手机号不正确',
    //     icon: 'loading'
    //   })

    // }
    // else if (!numNameSymVer.test(address)) {
    //   wx.showToast({
    //     title: '地址不正确',
    //     icon: 'loading'
    //   })

    // }
    // else if (!idCaedVer.test(idCardNum)) {
    //   wx.showToast({
    //     title: '身份证号不正确',
    //     icon: 'loading'
    //   })
    // }
     
    // else if (!letNumVer.test(engineModel)) {
    //   wx.showToast({
    //     title: '发动机型号不正确',
    //     icon: 'loading'
    //   })
    // } 
    // else if (!letNumVer.test(enginePower)) {
    //   wx.showToast({
    //     title: '功率不正确',
    //     icon: 'loading'
    //   })
    // } else if (!letNumVer.test(enginePlateNum)) {
    //   wx.showToast({
    //     title: '发动机编号不正确',
    //     icon: 'loading'
    //   })
    // } else if (!letNumVer.test(factoryNumber)) {
    //   wx.showToast({
    //     title: '出厂编号不正确',
    //     icon: 'loading'
    //   })
    // } else if (!numNameVer.test(workDayTime)) {
    //   wx.showToast({
    //     title: '工作时长不正确',
    //     icon: 'loading'
    //   })
    // } 
   


    // else {
      this.setData({
        fromData: e.detail.value,
        hiddenmodalput: !this.data.hiddenmodalput
      })

    // }
  },

  // 这个必须有吗？？？再加这个点击时间，不好对输入的数据进行判断？11？？
  // modalinput: function (e) {
  //     this.setData({
  //       hiddenmodalput: !this.data.hiddenmodalput
  //     })
  //   }
  // },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认  
  confirm: function () {
    var fromData = this.data.fromData;
    fromData.referenceUserImg = this.data.imgsUrl;
    fromData.referenceDeviceImg = this.data.equipmentImgsUrl;
    fromData.workTime=parseInt(fromData.workTime)
    console.log(fromData.isInvoice)
    if (fromData.isInvoice) {
      fromData.isInvoice = "1"

    } else {
      fromData.isInvoice = "0"
      fromData.referenceInvoiceImg = this.data.buyerImgsUrl;
    }
    console.log(fromData)
    this.setData({
      hiddenmodalput: true
    })
    wx.request({
      url: app.globalData.requestURL + '/yzUserMachinReference/saveUserMachinReferenceV2',
      method: 'POST',
      data: fromData,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        wx.showToast({
          title: "提交成功"
        })
        setTimeout(function () {
          wx.navigateBack({
            url: '/pages/index/index'
          })
        }, 1500) //延迟时间 这里是1秒  

        console.log(res.data)
      }
    })

  },
  bindChange: function (e) {
    //console.log(e);
    var val = e.detail.value
    var t = this.data.values;
    var cityData = this.data.cityData;

    if (val[0] != t[0]) {
      console.log('province no ');
      const citys = [];
      const countys = [];

      for (let i = 0; i < cityData[val[0]].sub.length; i++) {
        citys.push(cityData[val[0]].sub[i].name)
      }
      for (let i = 0; i < cityData[val[0]].sub[0].sub.length; i++) {
        countys.push(cityData[val[0]].sub[0].sub[i].name)
      }

      this.setData({
        province: this.data.provinces[val[0]],
        city: cityData[val[0]].sub[0].name,
        citys: citys,
        county: cityData[val[0]].sub[0].sub[0].name,
        countys: countys,
        values: val,
        value: [val[0], 0, 0]
      })

      return;
    }
    if (val[1] != t[1]) {
      console.log('city no');
      const countys = [];

      for (let i = 0; i < cityData[val[0]].sub[val[1]].sub.length; i++) {
        countys.push(cityData[val[0]].sub[val[1]].sub[i].name)
      }

      this.setData({
        city: this.data.citys[val[1]],
        county: cityData[val[0]].sub[val[1]].sub[0].name,
        countys: countys,
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      console.log('county no');
      this.setData({
        county: this.data.countys[val[2]],
        values: val
      })
      return;
    }


  },
  open: function () {
    this.setData({
      condition: !this.data.condition
    })
  },
  onLoad: function (options) {
    var wxmap = new QQMapWX({ key: 'PMQBZ-GOCW6-IBXS3-EAZ2X-5R5O5-BCFVO' })

    console.log("onLoad");
    var that = this;

    tcity.init(that);

    var cityData = that.data.cityData;


    const provinces = [];
    const citys = [];
    const countys = [];

    for (let i = 0; i < cityData.length; i++) {
      provinces.push(cityData[i].name);
    }
    console.log('省份完成');
    for (let i = 0; i < cityData[0].sub.length; i++) {
      citys.push(cityData[0].sub[i].name)
    }
    console.log('city完成');
    for (let i = 0; i < cityData[0].sub[0].sub.length; i++) {
      countys.push(cityData[0].sub[0].sub[i].name)
    }
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: function (res) {
        wxmap.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (res) {
            console.log(res);
            that.setData({
              'province': res.result.address_component.province,
              'city': res.result.address_component.city,
              'county': res.result.address_component.district
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
         
          }
        });
        console.log(res)
      },
      fail: function (res) { },
      complete: function (res) { },
    })
    that.setData({
      'provinces': provinces,
      'citys': citys,
      'countys': countys,
      'province': cityData[0].name,
      'city': cityData[0].sub[0].name,
      'county': cityData[0].sub[0].sub[0].name
    })
    console.log('初始化完成');


  },

  onReady: function () {

  },

  onShow: function () {

  },


  onHide: function () {

  },

  onUnload: function () {

  },

  onPullDownRefresh: function () {

  },


  onReachBottom: function () {

  },

  onShareAppMessage: function () {

  },

})